/**
 * @param {number} n
 * @return {number}
 */
export var binaryGap = function (n) {
  if (!(n & (n - 1))) return 0
  let ans = 0
  let count = 0
  while (n > 0) {
    let is1 = n & 1
    if (is1) {
      count = 1
    } else if (count > 0) {
      count++
    }
    ans = Math.max(count, ans)
    n = n >> 1
  }
  return ans
}

/**
 * @param {number} n
 * @return {number}
 */
export var binaryGap2 = function (n) {
  const nArr = n.toString(2).split('1')
  if (nArr.length < 3) return 0
  // let ans = 0
  // for (let i = 1; i < nArr.length - 1; i++) {
  //   ans = Math.max(ans, nArr[i].length + 1)
  // }
  // return ans
  return nArr.slice(1, nArr.length - 2).reduce((a, b) => {
    return Math.max(a, b.length + 1)
  }, 0)
}
